package cn.lg.soar.system.biz.modules.monitor.controller;

import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.mvc.annotations.DisabledTenantAccess;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.api.service.ILoginApi;
import cn.lg.soar.system.biz.modules.auth.entity.User;
import cn.lg.soar.system.biz.modules.auth.service.IUserService;
import cn.lg.soar.system.biz.modules.monitor.entity.RefreshToken;
import cn.lg.soar.system.biz.modules.monitor.model.RefreshTokenVO;
import cn.lg.soar.system.biz.modules.monitor.service.impl.RefreshTokenServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * @date 2021/10/16
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Slf4j
@Tag(name = "在线用户管理")
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/token")
public class TokenInfoController {

    @Autowired
    private RefreshTokenServiceImpl refreshTokenService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ILoginApi loginApi;

    @DisabledTenantAccess
    @Operation(summary = "在线用户")
    @GetMapping(value = "query", name = "在线用户")
    public HttpResult<PageResult<RefreshTokenVO>> query(PageQuery pageQuery, RefreshToken tokenInfo) {
        LambdaQueryWrapper<RefreshToken> wrapper = Wrappers.<RefreshToken>lambdaQuery()
                .ge(RefreshToken::getAccessExpires, LocalDateTime.now())
                .eq(Objects.nonNull(tokenInfo.getUserId()), RefreshToken::getUserId, tokenInfo.getUserId())
                .eq(Objects.nonNull(tokenInfo.getClientType()), RefreshToken::getClientType, tokenInfo.getClientType())
                .eq(Objects.nonNull(tokenInfo.getIp()), RefreshToken::getIp, tokenInfo.getIp());
        Page<RefreshToken> page = this.refreshTokenService.page(
                new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize()),
                wrapper
        );
        List<RefreshTokenVO> vos = page.getRecords().stream().map((x) -> {
            RefreshTokenVO vo = new RefreshTokenVO();
            BeanUtils.copyProperties(x, vo);
            return vo;
        }).collect(Collectors.toList());
        Map<Integer, List<RefreshTokenVO>> grouping = vos.stream().collect(Collectors.groupingBy(RefreshTokenVO::getUserType));
        List<RefreshTokenVO> tokens = grouping.get(0);
        if (tokens != null) {
            Set<Long> userIds = tokens.stream().map(RefreshTokenVO::getUserId).collect(Collectors.toSet());
            Map<?, String> userMap = userService.mapByIds(userIds, User::getNickname);
            for (RefreshTokenVO token : tokens) {
                token.setNickname(userMap.get(token.getUserId()));
            }
        }
        PageResult<RefreshTokenVO> result = new PageResult<>();
        result.setPageNo(pageQuery.getPageNo());
        result.setPageSize(pageQuery.getPageSize());
        result.setTotal(page.getTotal());
        result.setList(vos);
        return HttpResult.data(result);
    }

    @DisabledTenantAccess
    @Operation(summary = "强制下线")
    @PostMapping(value = "offline", name = "强制下线")
    public HttpResult<Void> offline(@RequestBody Set<Long> ids) {
        for (Long id : ids) {
            try {
                this.loginApi.logoutByTokenId(id);
            } catch (RuntimeException e) {
                log.error("退出登录失败", e);
            }
        }
        return HttpResult.success();
    }

}
